//
//  ViewController.m
//  综合练习
//
//  Created by Justsoso on 16/2/26.
//  Copyright © 2016年 NIIT. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIView *infoView;

@property (nonatomic,strong) NSArray *mArr;

@property (weak, nonatomic) IBOutlet UIButton *addBtn;
@property (weak, nonatomic) IBOutlet UIButton *removeBtn;

@end

@implementation ViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
     NSString *path = [[NSBundle mainBundle] pathForResource:@"shops" ofType:@"plist"];
    self.mArr = [[NSArray alloc] initWithContentsOfFile:path];
    
    
}
- (void)addImageView
{
    // 当前是第几个商品，可以根据当前infoView中的子视图计算
    int index = self.infoView.subviews.count;
    // 每行放几个商品
    int rowCount = 3;
    // 根据每行放几个，计算当前商品在第几行第几列
    int col = index % rowCount; // 行
    int row = index / rowCount; // 列
    // 图片的大小
    int imageW = 80;
    int imageH = 80;
    // 根据infoView总宽度和每行商品数量计算一下商品和每列的间隔大小
    int infoViewWidth = self.infoView.frame.size.width;
    int colMargin = (infoViewWidth - rowCount * imageW) / (rowCount - 1);
    int rowMargin = 20;
    // 计算图片实际的位置
    int imageX = col * (imageW + colMargin);
    int imageY = row * (imageH + rowMargin);
    // 得到当前商品的信息字典
    NSDictionary *d = self.mArr[index];
    UIView *view = [[UIView alloc] init];
    
    // 添加图片视频
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(imageX, imageY, imageW, imageH)];
    imageView.image = [UIImage imageNamed:d[@"icon"]];
    imageView.backgroundColor = [UIColor whiteColor];
    [view addSubview:imageView];
    
    // 添加文本标签
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(imageX, imageY+imageH, imageW, 10)];
    label.text = d[@"name"];
    label.font = [UIFont systemFontOfSize:10];
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor whiteColor];
    [view addSubview:label];
    
    [self.infoView addSubview:view];
}


- (IBAction)addBtnPressed:(id)sender
{
    
    [self addImageView];
    [self checkState];
    
}
- (IBAction)removeBtnPressed:(id)sender
{
    [[self.infoView.subviews lastObject] removeFromSuperview];
    [self checkState];
}

- (void)checkState
{
    self.removeBtn.enabled = (self.infoView.subviews.count > 0);
    self.addBtn.enabled = (self.infoView.subviews.count < self.mArr.count);
}

@end
